<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  description: '',
  sort: 0,
  status: 1,
  articleCount: 0
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 表单引用
const formRef = ref()

// 初始化数据
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = () => {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    tableData.value = [
      { id: 1, name: '技术分享', description: '分享技术相关文章', sort: 1, status: 1, articleCount: 15, createTime: '2023-01-01 10:00:00', updateTime: '2023-01-01 10:00:00' },
      { id: 2, name: '生活随笔', description: '生活感悟和随笔', sort: 2, status: 1, articleCount: 8, createTime: '2023-01-02 10:00:00', updateTime: '2023-01-02 10:00:00' },
      { id: 3, name: '学习笔记', description: '学习过程中的笔记记录', sort: 3, status: 1, articleCount: 12, createTime: '2023-01-03 10:00:00', updateTime: '2023-01-03 10:00:00' },
      { id: 4, name: '项目经验', description: '项目开发经验分享', sort: 4, status: 1, articleCount: 6, createTime: '2023-01-04 10:00:00', updateTime: '2023-01-04 10:00:00' }
    ]
    pagination.total = 4
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchData()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加分类'
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 显示编辑对话框
const showEditDialog = (row: any) => {
  dialogTitle.value = '编辑分类'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  form.id = row.id
  form.name = row.name
  form.description = row.description
  form.sort = row.sort
  form.status = row.status
  form.articleCount = row.articleCount
}

// 删除分类
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该分类吗? 删除后该分类下的文章将变为未分类状态。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除API请求
    setTimeout(() => {
      ElMessage.success('删除成功')
      fetchData()
    }, 500)
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      // 模拟API请求
      setTimeout(() => {
        ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
        dialogVisible.value = false
        fetchData()
      }, 500)
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = ''
  form.name = ''
  form.description = ''
  form.sort = 0
  form.status = 1
  form.articleCount = 0
}

// 状态格式化
const statusFormatter = (row: any) => {
  return row.status === 1 ? '启用' : '禁用'
}

// 状态标签类型
const statusTagType = (status: number) => {
  return status === 1 ? 'success' : 'info'
}

// 排序操作
const handleSort = (row: any, direction: 'up' | 'down') => {
  // 模拟排序API请求
  setTimeout(() => {
    ElMessage.success(`${direction === 'up' ? '上移' : '下移'}成功`)
    fetchData()
  }, 500)
}
</script>

<template>
  <div class="category-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="分类名称">
          <el-input v-model="searchForm.name" placeholder="请输入分类名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-button type="primary" :icon="Plus" @click="showAddDialog">添加分类</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="articleCount" label="文章数量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusFormatter(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="handleSort(row, 'up')" :disabled="row.sort === 1">上移</el-button>
              <el-button type="primary" size="small" @click="handleSort(row, 'down')" :disabled="row.sort === tableData.length">下移</el-button>
              <el-button type="success" :icon="Edit" size="small" @click="showEditDialog(row)">编辑</el-button>
              <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入分类描述" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.category-container {
  padding: 20px;
  height: calc(100vh - 30px);
  overflow-y: auto;
  box-sizing: border-box;
}

.search-card {
  margin-bottom: 20px;
}

/* 搜索区域样式优化 */
.search-card .el-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.search-card .el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}

.search-card .el-form-item:last-child {
  margin-right: 0;
}

/* 增加选择框宽度 */
.search-card .el-select {
  width: 150px;
}

.operation-area {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .category-container {
    padding: 10px;
  }
  
  .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .el-table .cell {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  
  .operation-area .el-button {
    margin-bottom: 10px;
  }
  
  .el-table .el-button {
    margin-bottom: 5px;
    margin-left: 0 !important;
  }
}

/* 表格内容溢出处理 */
.el-table .cell {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

/* 对话框样式优化 */
.el-dialog__body {
  padding: 20px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

/* 按钮间距 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 标签样式优化 */
.el-tag {
  margin-right: 5px;
}

/* 分页样式优化 */
.pagination-container .el-pagination {
  justify-content: flex-end;
}

/* 操作列按钮样式 */
.operation-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: nowrap;
  justify-content: center;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .category-container {
    padding: 10px;
  }
  
  .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .el-table .cell {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  
  .operation-area .el-button {
    margin-bottom: 10px;
  }
  
  .el-table .el-button {
    margin-bottom: 5px;
    margin-left: 0 !important;
  }
  
  .operation-buttons {
    flex-direction: column;
    gap: 3px;
  }
}
</style>